package com.ykdl.app.base;


import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.ykdl.app.R;
import com.ykdl.app.Utils.SystemBarTintManager;
import com.ykdl.app.base.BaseFragment.onNetWorkNoConnectListener;
import com.ykdl.app.bean.EndEvent;
import com.ykdl.app.bean.NetWorkStateBean;
import com.ykdl.app.view.CustomProgressDialog;

import de.greenrobot.event.EventBus;

/**
 * 作者 jiafeiyu 时间 2015-6-8 描述 Fragmentactivity基类
 */
public abstract class BaseFragmentActivity extends FragmentActivity {

	public AQuery mAQ;
	private SystemBarTintManager mTintManager;
	private CustomProgressDialog dialog;
	protected Button mLeft, mRight;
	protected TextView mTitle, remind,left_text;
	public RelativeLayout set_downbut;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.base_activity);
		mLeft = (Button) findViewById(R.id.left);
		mRight = (Button) findViewById(R.id.right);
		mTitle = (TextView) findViewById(R.id.title);
		remind = (TextView) findViewById(R.id.remind);
		left_text = (TextView) findViewById(R.id.left_text);
		set_downbut = (RelativeLayout) findViewById(R.id.set_downbut);
		dialog =new CustomProgressDialog(this, "",R.anim.frame,R.style.Custom_Progress);
		dialog.getWindow().setBackgroundDrawableResource(R.color.transparent); 
		mAQ = new AQuery(this);
		mAQ.id(R.id.left).clicked(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		EventBus.getDefault().register(this);
		isConnectInternet();
	}
	
	public final void setTopNav(int title, int left, OnClickListener onLeft,
			int right, OnClickListener onRight) {
		mTitle.setText(title);
		if (onLeft != null) {
			mLeft.setText(left);
			mLeft.setOnClickListener(onLeft);
			mLeft.setVisibility(View.VISIBLE);

		} else {
			mLeft.setVisibility(View.INVISIBLE);
		}
		if (onRight != null) {
			mRight.setText(right);
			mRight.setOnClickListener(onRight);
			mRight.setVisibility(View.VISIBLE);
		} else {
			mRight.setVisibility(View.INVISIBLE);
		}
	}

	/**
	 * 
	 * @param title
	 *            标题
	 * @param left
	 *            左边按钮上面的字
	 * @param leftPic
	 *            左边按钮的背景图片，没有设为0
	 * @param onLeft
	 *            左边按钮的点击事件，没有设为null
	 * @param right
	 *            右边按钮上面的字
	 * @param rightPic
	 *            右边按钮的背景图片，没有设为0
	 * @param onRight
	 *            右边按钮的点击事件，没有设为null
	 * @param titlePic
	 *            整个标题的背景图片，没有设为0
	 */
	// 设置各个Activity的title
	public final void setTopTitle(int title, int left, int leftPic,
			OnClickListener onLeft, int right, int rightPic,
			OnClickListener onRight, int titlePic) {
		if (titlePic != 0) {
			set_downbut.setBackgroundResource(titlePic);
		}
		left_text.setVisibility(View.VISIBLE);
		mTitle.setText(title);
		if (onLeft != null) {
			if (left != 0) {
//				mLeft.setText(left);
			} else {
//				mLeft.setText("");
			}
			if (leftPic != 0) {
				mLeft.setBackgroundResource(leftPic);
			}
			left_text.setOnClickListener(onLeft);
			mLeft.setOnClickListener(onLeft);
			mLeft.setOnClickListener(onLeft);
			mLeft.setVisibility(View.VISIBLE);
		} else {
			mLeft.setVisibility(View.INVISIBLE);
		}
		if (onRight != null) {
			if (right != 0) {
				mRight.setText(right);
			} else {
				mRight.setText(null);
			}
			if (rightPic != 0) {
				mRight.setBackgroundResource(rightPic);
			}
			mRight.setOnClickListener(onRight);
			mRight.setVisibility(View.VISIBLE);
		} else {
			mRight.setVisibility(View.INVISIBLE);
		}
	}

	public final void setTopTitle(String title, int left, int leftPic,
			OnClickListener onLeft, int right, int rightPic,
			OnClickListener onRight, int titlePic) {
		if (titlePic != 0) {
			set_downbut.setBackgroundResource(titlePic);
		}
		left_text.setVisibility(View.VISIBLE);
		mTitle.setText(title);
		if (onLeft != null) {
			if (left != 0) {
				mLeft.setText(left);
			} else {
				mLeft.setText("");
			}
			if (leftPic != 0) {
				mLeft.setBackgroundResource(leftPic);
			}
			left_text.setOnClickListener(onLeft);
			mLeft.setOnClickListener(onLeft);
			mLeft.setVisibility(View.VISIBLE);
		} else {
			mLeft.setVisibility(View.INVISIBLE);
		}
		if (onRight != null) {
			if (right != 0) {
				mRight.setText(right);
			} else {
				mRight.setText(null);
			}
			if (rightPic != 0) {
				mRight.setBackgroundResource(rightPic);
			}
			left_text.setOnClickListener(onLeft);
			mRight.setOnClickListener(onRight);
			mRight.setVisibility(View.VISIBLE);
		} else {
			mRight.setVisibility(View.INVISIBLE);
		}
	}

	public final void setTopTitle(String title, int left, int leftPic,
			OnClickListener onLeft, int right, int rightPic,
			OnClickListener onRight, int titlePic, boolean type) {
		if (titlePic != 0) {
			set_downbut.setBackgroundResource(titlePic);
		}

		mTitle.setText(title);
		left_text.setVisibility(View.VISIBLE);
		if (onLeft != null) {
			if (left != 0) {
//				mLeft.setText(left);
			} else {
//				mLeft.setText("");
			}
			if (leftPic != 0) {
				mLeft.setBackgroundResource(leftPic);
			}
			mLeft.setOnClickListener(onLeft);
			left_text.setOnClickListener(onLeft);
			mLeft.setVisibility(View.VISIBLE);
		} else {
			mLeft.setVisibility(View.INVISIBLE);
		}
		if (onRight != null) {
			if (right != 0) {
				mRight.setText(right);
			} else {
				mRight.setText(null);
			}
			if (rightPic != 0) {
				mRight.setBackgroundResource(rightPic);
			}
			mRight.setOnClickListener(onRight);
			mRight.setVisibility(View.VISIBLE);
		} else {
			mRight.setVisibility(View.INVISIBLE);
		}

		if (type) {
			remind.setVisibility(View.VISIBLE);
		}
	}

	public void changeSystemBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			setTranslucentStatus(true);
		}

		SystemBarTintManager tintManager = new SystemBarTintManager(this);
		tintManager.setStatusBarTintEnabled(true);
		tintManager.setStatusBarTintColor(getResources().getColor(R.color.base_title_blue));

		//
		// mTintManager = new SystemBarTintManager(this);
		// mTintManager.setStatusBarTintEnabled(true);
		// mTintManager.setNavigationBarTintEnabled(true);
		// mTintManager.setTintColor(Color.parseColor("#38aafc"));
	}
	@TargetApi(19)
	private void setTranslucentStatus(boolean on) {
		Window win = getWindow();
		WindowManager.LayoutParams winParams = win.getAttributes();
		final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
		if (on) {
			winParams.flags |= bits;
		} else {
			winParams.flags &= ~bits;
		}
		win.setAttributes(winParams);
	}
	public void changeSystemBarToWhite() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			setTranslucentStatus(true);
		}

		SystemBarTintManager tintManager = new SystemBarTintManager(this);
		tintManager.setStatusBarTintEnabled(true);
		tintManager.setStatusBarTintColor(getResources().getColor(R.color.base_title_blue));
	}
	public void setTitle(String title) {
		mLeft.setVisibility(View.INVISIBLE);
		mRight.setVisibility(View.INVISIBLE);
		if (!TextUtils.isEmpty(title)) {
			mAQ.id(R.id.title).text(title);
		}
	}
	public final void setTopNav(String title) {
		mTitle.setText(title);
	}
	public void setTitleHide(){
		mAQ.id(R.id.rl).visibility(View.GONE);
	}
	public void setTitleShow(){
		mAQ.id(R.id.rl).visibility(View.VISIBLE);
	}
	public void setTitle(String title,String backColor) {
		if (!TextUtils.isEmpty(title)) {
			mAQ.id(R.id.title).text(title);
		}
		if(!backColor.isEmpty()){
			mAQ.id(R.id.rl).getView().setBackgroundColor(Color.parseColor(backColor));
		}
	}

	public void setRightListener(OnClickListener listener) {
		mAQ.id(R.id.right).clicked(listener);
	}

	public void setLeftListener(OnClickListener listener) {
		mAQ.id(R.id.left).clicked(listener);
	}
	
	public  Button getRightButton(){
		return mAQ.id(R.id.left).getButton();
	}

	/**
	 * 设置右边的按钮是否显示
	 * 
	 * @param isShow
	 */
	public void setRightShowOrHidden(boolean isShow) {
		if (isShow) {
			mAQ.id(R.id.right).visibility(View.VISIBLE);
		} else {
			mAQ.id(R.id.right).visibility(View.INVISIBLE);
		}
	}
	/**
	 * 设置左边的按钮是否显示
	 * 
	 * @param isShow
	 */
	public void setLeftShowOrHidden(boolean isShow) {
		if (isShow) {
			mAQ.id(R.id.left).visibility(View.VISIBLE);
		} else {
			mAQ.id(R.id.left).visibility(View.INVISIBLE);
		}
	}
	/**
	 * 设置右边按钮背景图片
	 * 
	 * @param drawle
	 */
	public void setRightBackground(int drawle) {
		mAQ.id(R.id.right).background(drawle);
	}

	public void SetContentLayout(int layoutResId) {
		LinearLayout llContent = (LinearLayout) findViewById(R.id.content);
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		View v = inflater.inflate(layoutResId, null);
		if (null != v) {

			llContent.addView(v, params);
		}
	}

	// // 返回键的处理
	// @Override
	// public void onBackPressed() {
	// AlertDialog dlg = new AlertDialog.Builder(this)
	// .setTitle("退出")
	// .setMessage(
	// "您确认要退出 " + this.getString(R.string.app_name) + " 吗？")
	// // 设置自定义对话框的样式
	// .setPositiveButton("确定", // 设置"确定"按钮
	// new DialogInterface.OnClickListener() // 设置事件监听
	// {
	// public void onClick(DialogInterface dialog,
	// int whichButton) {
	// // 完全退出应用
	// android.os.Process
	// .killProcess(android.os.Process.myPid());
	// System.exit(0);
	// }
	// })
	// .setNegativeButton("取消", new DialogInterface.OnClickListener() {
	//
	// @Override
	// public void onClick(DialogInterface dialog, int which) {
	//
	// }
	// }).create();// 创建
	// dlg.show();
	// }

	// 带参数的Activity
	protected void startActivity(Activity from, Class<?> to, Bundle bundle,
			boolean isFinish) {
		Intent intent = new Intent();
		if (bundle != null)
			intent.putExtras(bundle);
		intent.setClass(from, to);
		startActivity(intent);
		if (isFinish) {
			from.finish();
		}
	}

	// 带参数的Activity
	protected void startActivity(Activity from, Class<?> to, Intent intent,
			int requestCode, boolean isFinish) {
		intent.setClass(from, to);
		startActivityForResult(intent, requestCode);
		if (isFinish) {
			from.finish();
		}
	}

	// 带参数的Activity
	protected void startActivity(Activity from, Class<?> to) {
		Intent intent = new Intent();
		intent.setClass(from, to);
		intent.putExtra("from", from.toString());
		startActivity(intent);
	}

	// 带参数的Activity
	protected void startActivity(Activity from, Class<?> to, int requestCode,
			boolean isFinish) {
		Intent intent = new Intent();
		intent.setClass(from, to);
		startActivityForResult(intent, requestCode);
		if (isFinish) {
			from.finish();
		}
	}

	/**
	 * restartApplication(重启应用)
	 */
	protected void restartApplication() {
		Intent i = getBaseContext().getPackageManager()
				.getLaunchIntentForPackage(getBaseContext().getPackageName());
		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(i);
	}

	/**
	 * sp的保存和获取(默认"config")
	 */
	protected SharedPreferences getSharedPreferences() {
		return getSharedPreferences("config", Context.MODE_PRIVATE);
	}

	protected String getSharedPreferencesValue(String key) {
		SharedPreferences sp = getSharedPreferences("config",
				Context.MODE_PRIVATE);
		return sp.getString(key, "");
	}

	protected String getSharedPreferencesValue(String filename, String key) {
		SharedPreferences sp = getSharedPreferences(filename,
				Context.MODE_PRIVATE);
		return sp.getString(key, "");
	}

	protected void saveSharedPreferencesValue(String key, String value) {
		SharedPreferences sp = getSharedPreferences("config",
				Context.MODE_PRIVATE);
		Editor edit = sp.edit();
		edit.putString(key, value);
		edit.commit();
	}

	protected void saveSharedPreferencesValue(String key, Boolean value) {
		SharedPreferences sp = getSharedPreferences("config",
				Context.MODE_PRIVATE);
		Editor edit = sp.edit();
		edit.putBoolean(key, value);
		edit.commit();
	}

	protected void saveSharedPreferencesValue(String filename, String key,
			String value) {
		SharedPreferences sp = getSharedPreferences(filename,
				Context.MODE_PRIVATE);
		Editor edit = sp.edit();
		edit.putString(key, value);
		edit.commit();
	}

	protected String getString(TextView textView) {
		if (textView == null) {
			return null;
		}
		return textView.getText().toString().trim();
	}

	/**
	 * 设置 出错的提示
	 * 
	 * @param err
	 *            err,错误提示，
	 * @param tip
	 *            tip 应该操作
	 */
	protected void showErrorTip(String err, String tip) {
		mAQ.id(R.id.error_view).visibility(View.VISIBLE);
		mAQ.id(R.id.content).visibility(View.GONE);
		mAQ.id(R.id.tv_error_text).text(err);
	}

	/**
	 * 隐藏 出错的提示
	 */
	protected void hidErrorTip() {
		mAQ.id(R.id.error_view).visibility(View.GONE);
		mAQ.id(R.id.content).visibility(View.VISIBLE);
	}

	/**
	 * 显示loading
	 */
	public void showLoading() {
		dialog.show();
	}

	/**
	 * 隐藏loading
	 */
	public void hiddenLoading() {
		dialog.dismiss();
	}

	/**
	 * 显示content
	 */
	protected void showContent() {
		mAQ.id(R.id.content).visibility(View.VISIBLE);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// MobclickAgent.onPageStart("SplashScreen");
		// MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		// MobclickAgent.onPageEnd("SplashScreen");
		// MobclickAgent.onPause(this);
	}

	@Override
	protected void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	/**
	 * 收到EndEvent的activity，会finish掉自己
	 * 
	 * @param event
	 */
	public void onEventMainThread(EndEvent event) {
		if (event != null) {
			finish();
		}
	}

	/**
	 * 判断是否有网络，如果没有网络，则显示没有数据页
	 * 
	 * @return
	 */
	private boolean isConnect = true;
	public boolean isConnectInternet() {
		boolean isConnnect = false;
		final ConnectivityManager conManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		final NetworkInfo networkInfo = conManager.getActiveNetworkInfo();

		if (networkInfo != null) {
			isConnnect = networkInfo.isAvailable();
		}
		if (!isConnnect) {
			showErrorTip("都什么年代了，居然没有网！", null);
			isConnect = false;
		}
		return isConnnect;
	}
	/**
	 * 显示一个Toast
	 */
	public void showToast(String content){
		Toast.makeText(this, content, 0).show();
	}
	
	/**
	 * 已经有网，如果之前没有网，则，重新加载数据
	 * 
	 * @param event
	 */
	public void onEventMainThread(NetWorkStateBean event) {
		if (event != null&&event.isConnect()) {
			if (!isConnect) {
				hidErrorTip();
			}
		}
		if (mConnectListener!=null&&event.isConnect()) {
			mConnectListener.onConnect(event.isConnect());
		}
		
	}
	private onNetWorkNoConnectListener mConnectListener;
	
	
	public void setmConnectListener(onNetWorkNoConnectListener mConnectListener) {
		this.mConnectListener = mConnectListener;
	}
}
